package com.ljx.demo6.dao;

import com.ljx.demo6.domain.NewsInfo;
import com.ljx.demo6.utils.DataBaseUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-05-22  14:20
 */
public class NewsDao {

    public static List<NewsInfo> getNewsAll() throws SQLException {
        List<NewsInfo> res = new ArrayList<>();
        Connection connection = DataBaseUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from tb_news");
        ResultSet resultSet = preparedStatement.executeQuery();
        while(resultSet.next()){
            Long id = resultSet.getLong("id");
            String title = resultSet.getString("title");
            String content = resultSet.getString("content");
            String type = resultSet.getString("type");
            Date createTime = resultSet.getDate("create_time");
            Date updateTime = resultSet.getDate("update_time");
            res.add(new NewsInfo(id, title, content, type, createTime, updateTime));
        }
        return res;
    }

    public static boolean deleteNewsById(Long id) throws SQLException {
        Connection connection = DataBaseUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("delete from tb_news where id = ?");
        preparedStatement.setLong(1, id);
        int resultSet = preparedStatement.executeUpdate();

        return resultSet > 0;
    }

    public static boolean updateNewsById(NewsInfo newsInfo) throws SQLException {
        Connection connection = DataBaseUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("update tb_news set title = ?, content = ?, type = ? where id = ?");
        preparedStatement.setString(1, newsInfo.getTitle());
        preparedStatement.setString(2, newsInfo.getContent());
        preparedStatement.setString(3, newsInfo.getType());
        preparedStatement.setLong(4, newsInfo.getId());
        int resultSet = preparedStatement.executeUpdate();

        return resultSet > 0;
    }

    public static boolean saveNews(NewsInfo newsInfo) throws SQLException {
        Connection connection = DataBaseUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("insert into tb_news (title, content, type) values (?, ?, ?)");
        preparedStatement.setString(1, newsInfo.getTitle());
        preparedStatement.setString(2, newsInfo.getContent());
        preparedStatement.setString(3, newsInfo.getType());
        int resultSet = preparedStatement.executeUpdate();

        return resultSet > 0;
    }
}
